<template>
  <div
    v-loading="listLoading"
    class="editor"
    :element-loading-text="elementLoadingText"
  >
    <editor-header />
    <div class="editor-body">
      <main ref="editor-content" class="editor-content">
        <workspace />
      </main>
      <aside class="editor-nav">
        <editor-aside />
      </aside>
      <aside class="editor-ads">
        <element-form />
      </aside>
    </div>
    <footer class="editor-footer">
      <button-route />
    </footer>
    <ImageEdit ref="image-edit" />
  </div>
</template>

<script>
  import EditorHeader from './components/EditorHeader'
  import Workspace from './components/Workspace'
  import EditorAside from './components/EditorAside'
  import ElementForm from './components/ElementForm'
  import ButtonRoute from './components/ButtonRoute'
  import ImageEdit from './components/ImageEdit'
  import { getOne, doEdit } from '@/api/topic'
  export default {
    name: 'Editor',
    root: true,
    components: {
      Workspace,
      EditorAside,
      EditorHeader,
      ElementForm,
      ButtonRoute,
      ImageEdit,
    },
    props: {
      topicKey: {
        type: String,
        required: true,
      },
    },
    data() {
      return {
        elementLoadingText: '正在加载...',
        listLoading: false,
        topic: {},
        data: {},
        doms: [],
        routes: {},
        domIndex: -1,
        baseApi: '/_topic/',
        baseUrl: '',
      }
    },
    computed: {
      dom() {
        const dom = this.doms[this.domIndex]
        return dom
      },
    },
    created() {
      this.fetchData()
    },
    mounted() {
      const timer = setInterval(() => {
        this.setCache()
        this.$baseMessage('自动缓存数据成功', 'info')
      }, 5 * 60 * 1000)
      this.$once('hook:beforeDestroy', function () {
        clearInterval(timer)
      })
    },
    methods: {
      addDom(dom) {
        const lastDom = this.doms[this.doms.length - 1]
        dom.sort = lastDom ? lastDom.sort + 1 : 1
        const len = this.doms.push(dom)
        this.setDomIndex(len - 1)
        if (dom.id && dom.type === 'button') {
          this.addRoute(dom.id)
        }
      },
      addRoute(id) {
        this.routes[id] = {
          left: '',
          right: '',
          up: '',
          down: '',
        }
      },
      setDomIndex(index) {
        if (typeof index !== 'number') return
        this.domIndex = index
        let layerStyle = document.head.querySelector('#editor-layer')
        if (!layerStyle) {
          layerStyle = document.createElement('style')
          layerStyle.id = 'editor-layer'
          document.head.appendChild(layerStyle)
        }
        layerStyle.innerHTML = `
          #editor-layer-table tr:nth-child(${index + 1}) {
            background: #b3d6f6;
          }
        `
      },
      reSortDoms(index) {
        let sort = 1
        for (const dom of this.doms) {
          this.$set(dom, 'sort', sort++)
        }
        this.setDomIndex(index)
      },
      deleteDom(index) {
        if (this.dom.type === 'button') {
          delete this.routes[this.dom.id]
        }
        this.doms.splice(index, 1)
        if (this.doms.length) {
          this.setDomIndex(0)
        } else {
          this.domIndex = -1
        }
        this.reSortDoms()
      },
      cleanCache() {
        sessionStorage.removeItem(this.$options.name)
      },
      getCache() {
        const cacheStr = sessionStorage.getItem(this.$options.name)
        if (cacheStr) {
          return JSON.parse(cacheStr)
        }
        return null
      },
      setCache() {
        sessionStorage.setItem(
          this.$options.name,
          JSON.stringify({
            topic: this.topic,
            data: this.data,
            doms: this.doms,
            routes: this.routes,
            domIndex: this.domIndex,
          })
        )
      },
      async fetchData() {
        const cache = this.getCache()
        if (cache) {
          this.data = cache.data
          this.topic = cache.topic
          this.doms = cache.doms
          this.routes = cache.routes
          if (typeof cache.domIndex !== 'undefined') {
            this.setDomIndex(cache.domIndex)
          } else if (this.doms.length) {
            this.setDomIndex(0)
          }
          return
        }
        this.listLoading = true
        const { data: topic } = await getOne(this.baseApi, this.topicKey)
        let { data: jsonStr } = topic
        this.topic = topic
        jsonStr =
          jsonStr ||
          `{
          "background": "",
          "width": 1280,
          "height": 720,
          "doms": [],
          "routes": {}
        }`
        this.listLoading = false
        try {
          this.data = JSON.parse(jsonStr)
          this.doms = this.data.doms || []
          this.routes = this.data.routes || {}
          for (const dom of this.doms) {
            if (dom.id) {
              this.routes[dom.id] = this.routes[dom.id] || {
                left: '',
                right: '',
                up: '',
                down: '',
              }
            }
          }
          if (this.doms.length) {
            this.setDomIndex(0)
          }
          this.setCache()
        } catch (error) {
          console.log(error)
          this.$baseMessage('数据格式错误，不是有效的json格式', 'error')
        }
      },
      async handleEdit() {
        try {
          this.listLoading = true
          this.data.doms = this.doms
          for (const dom of this.doms) {
            dom.focus_left = dom._focus_left + dom.left
            dom.focus_top = dom._focus_top + dom.top
          }
          this.topic.data = JSON.stringify(this.data)
          this.setCache()
          await doEdit(this.baseApi, this.topic)
          this.listLoading = false
          this.$baseMessage('数据保存成功', 'success')
        } catch (error) {
          console.log(error)
          this.listLoading = false
          this.$baseMessage('数据保存失败', 'error')
        }
      },
    },
  }
</script>

<style scoped>
  .editor {
    color: #ecf0f1;
    display: flex;
    min-height: 100vh;
    flex-direction: column;
  }

  .editor-footer {
    height: 58px;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .editor-footer {
    border-top: 1px solid #425668;
    background: #2a3f54;
  }

  .editor-body {
    display: flex;
    flex: 1;
  }

  .editor-content {
    flex: 1;
    position: relative;
    overflow: scroll;
  }

  .editor-nav,
  .editor-ads {
    /* 两个边栏的宽度设为12em */
    flex: 0 0 230px;
    background: #2a3f54;
  }

  .editor-ads {
    position: relative;
    overflow: auto;
  }

  .editor-nav {
    /* 导航放到最左边 */
    order: -1;
  }
</style>
